//
//  SearchPageViewController.m
//  LuckyRadio
//
//  Created by Mr、J on 15/11/25.
//  Copyright © 2015年 chenjun. All rights reserved.
//

#import "SearchPageViewController.h"
#import "RESideMenu.h"
#import "CustomerNetworking.h"
#import "SearchPageModel.h"
#import "SongsModel.h"
#import <MJRefresh.h>
#import "SearchPageTableViewCell.h"
#import "LGCLastViewController.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define WIDTH_PRO(X) (X)*(SCREEN_WIDTH/375)

#define HEIGHT_PRO(Y) (Y)*(SCREEN_HEIGHT/667)
@interface SearchPageViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UIView *totalView;

@property (nonatomic, retain) UILabel *titleLabel;

@property (nonatomic, retain) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, retain) NSMutableArray *songArray;

@property (nonatomic, retain) UIView *promptView;

@property (nonatomic, retain) UIAlertController *alert;

@end

@implementation SearchPageViewController
- (void)dealloc
{
    [_searchBar release];
    [_tableView release];
    [_totalView release];
    [_titleLabel release];
    [_dataArray release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    self.songArray = [NSMutableArray array];
    self.page = 1;
    [self createSearchBar];
    [self loadData];
    [self createViews];


}
-(void)createSearchBar
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(rightnav)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(WIDTH_PRO(10), HEIGHT_PRO(10), WIDTH_PRO(30), HEIGHT_PRO(30));
    [button setImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backToSlider) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, WIDTH_PRO(300), HEIGHT_PRO(45))];
    self.searchBar.delegate = self;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.barStyle=UIBarStyleDefault;
    self.searchBar.placeholder=@"搜索感兴趣的内容";
    self.searchBar.keyboardType=UIKeyboardTypeNamePhonePad;
    self.navigationItem.titleView = self.searchBar;
    [_searchBar release];
    
}

-(void)loadData
{
    [CustomerNetworking customerWithURL:@"http://so.ard.iyyin.com/sug/billboard?app=ttpod&v=v8.1.1.2015110616&user_id=0&mid=iPhone5S&f=f234&s=s310&imsi=&hid=&splus=9.1&active=1&net=2&openudid=e97c1f17f916efa173065a10152c7506e65b60f7&idfa=5FBD2BF5-1484-4C9B-A138-4D9CE22EADB5&utdid=VkKezJUW5SwDAGga0yzrZnyO&alf=700606&bundle_id=com.ttpod.music&latitude=38.89680989464323&longtitude=121.5286713817766" andParamer:nil andBlock:^(id response) {
        
        for (NSDictionary *dic in [response objectForKey:@"data"]) {
            SearchPageModel *searchPageModel = [SearchPageModel modelWithDictionary:dic];
            [self.dataArray addObject:searchPageModel];
        }
        [self createButton];

    }];
}

-(void)createViews
{
    self.totalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT_PRO(64))];
    [self.view addSubview:self.totalView];
    [_totalView release];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH_PRO(10), HEIGHT_PRO(100), SCREEN_WIDTH - WIDTH_PRO(20), HEIGHT_PRO(20))];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.text = @"搜索热词";
    [self.totalView addSubview:self.titleLabel];
    [_titleLabel release];
    
}

-(void)createButton
{
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 2; j++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(WIDTH_PRO(30) + WIDTH_PRO(150) * j, HEIGHT_PRO(150) + HEIGHT_PRO(50) * i, WIDTH_PRO(150), HEIGHT_PRO(50));
                SearchPageModel *searchPageModel = _dataArray[2 * i + j];
                [button setTitle:searchPageModel.val forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:15];
                [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.totalView addSubview:button];
            }
        }

    }
-(void)btnAction:(UIButton *)sender
{
    self.searchBar.text = sender.titleLabel.text;
    
    [self searchBarSearchButtonClicked:self.searchBar];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [_songArray removeAllObjects];
    [self.totalView removeFromSuperview];
   
    
    NSString *searchstr = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=%ld&size=50&app=ttpod&v=v8.1.1.2015110616&user_id=0&mid=iPhone5S&f=f234&s=s310&imsi=&hid=&splus=9.1&active=1&net=2&openudid=e97c1f17f916efa173065a10152c7506e65b60f7&idfa=5FBD2BF5-1484-4C9B-A138-4D9CE22EADB5&utdid=VkKezJUW5SwDAGga0yzrZnyO&alf=700606&bundle_id=com.ttpod.music&latitude=38.89680989464323&longtitude=121.5286713817766",self.searchBar.text, _page];
    searchstr = [searchstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [CustomerNetworking customerWithURL:searchstr andParamer:nil andBlock:^(id response) {
        
        for (NSDictionary *dic in [response objectForKey:@"data"]) {
            SongsModel *songsModel = [SongsModel modelWithDictionary:dic];
            
            [self.songArray addObject:songsModel];
        }
        
        [self.tableView reloadData];
        
        
        if (self.songArray.count == 0) {
            
            [self createView];
        }else{
            
            [self createTableView];
        }
        
    }];
    
}

-(void)loadTableViewData
{
    NSString *searchstr = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=%ld&size=50&app=ttpod&v=v8.1.1.2015110616&user_id=0&mid=iPhone5S&f=f234&s=s310&imsi=&hid=&splus=9.1&active=1&net=2&openudid=e97c1f17f916efa173065a10152c7506e65b60f7&idfa=5FBD2BF5-1484-4C9B-A138-4D9CE22EADB5&utdid=VkKezJUW5SwDAGga0yzrZnyO&alf=700606&bundle_id=com.ttpod.music&latitude=38.89680989464323&longtitude=121.5286713817766",self.searchBar.text, _page];
    searchstr = [searchstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [CustomerNetworking customerWithURL:searchstr andParamer:nil andBlock:^(id response) {
        
        for (NSDictionary *dic in [response objectForKey:@"data"]) {
            SongsModel *songsModel = [SongsModel modelWithDictionary:dic];
            
            [self.songArray addObject:songsModel];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
        if (self.songArray.count == 0) {
            
            [self createView];
        }
    }];
    

}

-(void)createView
{
    self.promptView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT_PRO(64), SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT_PRO(64))];
    self.promptView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.promptView];
    [self.promptView release];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/ 2 -  WIDTH_PRO(100), HEIGHT_PRO(20), WIDTH_PRO(30), HEIGHT_PRO(30))];
    imageView.image = [UIImage imageNamed:@"ic_list_item_report@3x"];
    [self.promptView addSubview:imageView];
    [imageView release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - WIDTH_PRO(60), HEIGHT_PRO(10), SCREEN_WIDTH - WIDTH_PRO(20), HEIGHT_PRO(50))];
    label.textColor = [UIColor grayColor];
    label.text = @"没有找到相关内容~";
    [self.promptView addSubview:label];
    [label release];
    
}


-(void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT_PRO(64), SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT_PRO(64)) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.tableView.mj_footer beginRefreshing];
        _page += 1;
        [self loadTableViewData];
        
    }];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _songArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEIGHT_PRO(70);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SongsModel *songsModel = _songArray[indexPath.row];
    SearchPageTableViewCell *cell = [SearchPageTableViewCell searchPageTableViewCellWith:tableView];
    cell.songsModel = songsModel;
    cell.numLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
    return cell;
}

-(void)backToSlider
{
    [self.sideMenuViewController presentLeftMenuViewController];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SongsModel *songModel = [_songArray objectAtIndex:indexPath.row];
    LGCLastViewController *lgcLastView = [LGCLastViewController shareLastViewController];
    lgcLastView.indexRow = indexPath.row;
    if (songModel.auditionList.count != 0) {
        if (songModel.auditionList.count == 3){
            lgcLastView.playUrl = [songModel.auditionList[2] objectForKey:@"url"];
            lgcLastView.strTitle = songModel.name;
        }else if (songModel.auditionList.count == 2){
            lgcLastView.playUrl = [songModel.auditionList[1] objectForKey:@"url"];
            lgcLastView.strTitle = songModel.name;
        }else {
            lgcLastView.playUrl = [songModel.auditionList[0] objectForKey:@"url"];
            lgcLastView.strTitle = songModel.name;
        }
    }
    lgcLastView.tempArray = _songArray;
    
    
    [self.navigationController presentViewController:lgcLastView animated:YES completion:nil];
}

-(void)rightnav
{
    if (![self.searchBar.text isEqualToString:@""]) {
        [self.searchBar resignFirstResponder];
        [_songArray removeAllObjects];
        [self.totalView removeFromSuperview];
        [self loadTableViewData];
        
    }else{
        
        self.alert = [UIAlertController alertControllerWithTitle:nil message:@"没有找到相关信息" preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:self.alert animated:YES completion:nil];
        
        [self performSelector:@selector(dimissAlert:) withObject:self.alert afterDelay:1.0];
    }
}

- (void) dimissAlert:(UIAlertController *)alert {
    if(alert)     {
        [self dismissViewControllerAnimated:alert completion:nil];
         }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
